package com.ali.niofiletransfer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class NIOFileTransferServer {
    public static void main(String[] args) {
        try {
            //构建监听服务
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            //设置监听服务为非阻塞状态
            serverSocketChannel.configureBlocking(false);
            //绑定监听端口
            serverSocketChannel.bind(new InetSocketAddress(8080));

            while (true) {
                //获取客户端连接
                SocketChannel socketChannel = serverSocketChannel.accept();
                if (socketChannel != null) {
                    System.out.println("接收客户端连接");
                    long startTime = System.currentTimeMillis();
                    long total = handle(socketChannel);
                    long endTime = System.currentTimeMillis();
                    System.out.println("耗时：" + (endTime - startTime) + "，接收字节数：" + total);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 处理客户端连接
     */
    private static long handle(SocketChannel socketChannel) {
        //构建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        int length;
        long total = 0;
        Path path = Paths.get("C:\\Users\\Administrator\\Desktop\\testCopy.mobi");

        //构建文件通道
        try (FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE)) {
            while (true) {
                //写入内容至缓冲区
                length = socketChannel.read(byteBuffer);
                if (length > 0) {
                    //读写切换
                    byteBuffer.flip();
                    //写入内容至通道
                    fileChannel.write(byteBuffer);
                    //清理缓冲区
                    byteBuffer.clear();
                    total = total + length;
                } else if (length == 0) {
                    break;
                } else if (length == -1) {
                    System.out.println("客户端断开连接");
                    break;
                }
            }
        } catch (Exception e) {
            System.out.println("客户端断开连接");
        }
        return total;
    }
}
